<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enum'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const store = useUserStore()
const route = useRoute()

const list = ref<Message[]>([])
const consult = ref<ConsultOrderItem>()

// 1. 建立和关闭socket连接
let socket: Socket
onMounted(() => {
  // 1.1 建立连接 io('服务器地址', 配置项)
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  // 1.2 监听连接是否建立成功
  socket.on('connect', () => {
    // 清空数据数组
    list.value = []

    // 2. 获取聊天记录(默认消息)
    socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
      // 2.1 处理默认消息
      const arr: Message[] = []
      data.forEach((item, i) => {
        // ---------------------
        // 记录每段消息的开始时间，作为下一次请求的开始时间
        if (i === 0) time.value = item.createTime
        // ---------------------
        // 2.1.2 创建一条时间消息
        arr.push({
          id: item.createTime,
          msgType: MsgType.Notify,
          createTime: item.createTime,
          msg: {
            content: item.createTime
          },
          noScroll: initialMsg.value === false // flase: 滚动  true: 不滚动
        })
        // 2.1.2 把其它消息放入数组
        // arr.push(...item.items)
        item.items.forEach((m) => {
          arr.push({ noScroll: initialMsg.value === false, ...m })
        })
      })
      // 2.2 把处理好的数据放入列表
      list.value.unshift(...arr)

      // ------------------------------------------
      // 3.1 关闭刷新效果
      loading.value = false
      // 3.2 判断是否有数据？没有提示 没有聊天记录了
      if (!data.length) {
        return showToast('没有聊天记录了')
      }
      // 3.3 如果是初始化获取的聊天，需要滚动到最底部
      // 如果是第二，三...次获取消息,不需要滚动到底部
      if (initialMsg.value) {
        nextTick(() => {
          window.scrollTo({ left: 0, top: document.body.scrollHeight })
          initialMsg.value = false // 不是初次
          socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        })
      }
    })
  })

  // 1.3 错误异常消息
  socket.on('error', (event) => {
    console.log('error', event)
  })

  // 1.4 已经断开连接
  socket.on('disconnect', () => {
    console.log('disconnect')
  })
})

onUnmounted(() => {
  // 关闭连接
  socket.close()
})

// 2. 获取订单详情
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data

  // 订单状态发生变化处理
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
})

// 3. 发送文字和图片
const sendText = (text: string) => {
  // 3.1 把文字包装成一条文字消息发给服务器
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

onMounted(() => {
  socket.on('receiveChatMsg', async (msg) => {
    // 1.1 把消息对象放入消息数组
    list.value.push(msg)

    // 1.2 让页面滚动到最底部
    await nextTick()
    window.scrollTo({ left: 0, top: document.body.scrollHeight })

    // 1.3 标识消息已读
    socket.emit('updateMsgStatus', msg.id)
  })
})

// 4. 获取聊天记录
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD hh:mm:ss')) // 记录每段消息的开始时间
const initialMsg = ref(true) // 记录是否是初次获取历史消息
const onRefresh = () => {
  // 4.1 发送获取聊天记录的事件
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

// 5. 评价
const completeEva = (score: number) => {
  // 5.1 找到待评价消息
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  // 5.2 如果找到了
  if (item) {
    item.msgType = MsgType.CardEva // 修改消息的类型
    item.msg.evaluateDoc = { score } // 加评价对象
  }
}
provide('consult', consult)
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list" />
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
